/**
 * 半球体生成 - L5
 * @author lonphy
 * @version 0.1
 */
(function(L5) {
	"use strict";
	function initConstructor() {
		/**
		 * 半球体
		 * @param radius {Number}  球体半径
		 */
		L5.Geometry.HalfSphere = function (radius) {
			this.radius = radius || 10;
			this.vertices = [];
			this.indices = [];
			this.materialLibrary = {};
			this.maters = [];
			this.create();
		};
	}
	function initMethods() {
		let $fn = L5.Geometry.HalfSphere.prototype;

		// 纬度和经度将被平分的份数
		L5.define(L5.Geometry.HalfSphere, {
			LATITUDE_BANDS: 30,
			LONGITUDE_BANDS: 30
		});

		$fn.create = function () {
			let vertex = this.vertices,
				indices = this.indices,
				first, second,
				latBands = L5.Geometry.HalfSphere.LATITUDE_BANDS,
				lonBands = L5.Geometry.HalfSphere.LONGITUDE_BANDS,
				radius = this.radius;

			for (let i = 0; i <= latBands; ++i) {
				let theta = i * Math.PI / (2*latBands);
				let sinTheta = Math.sin(theta);
				let cosTheta = Math.cos(theta);

				for (let j = 0; j <= lonBands; j++) {
					var phi = j * 2 * Math.PI / lonBands;
					var sinPhi = Math.sin(phi);
					var cosPhi = Math.cos(phi);

					var x = cosPhi * sinTheta;
					var y = cosTheta;
					var z = sinPhi * sinTheta;
					var u = 1 - (j / lonBands);
					var v = 1 - (i / latBands);

					vertex.push(radius * x, radius * y, radius * z);	// position
					vertex.push(x, y, z);								// normal
					vertex.push(u, v, 0);								// uv and texture id
				}
			}

			for (let i = 0; i < latBands; ++i) {
				for (let j = 0; j < lonBands; ++j) {
					first = (i * (lonBands + 1)) + j;
					second = first + lonBands + 1;

					indices.push(first, second, first + 1, second, second + 1, first + 1);
				}
			}
		};

		$fn.setMaterial = function (name, mater) {
			this.materialLibrary[name] = mater;
			this.maters.push(name);
		};

		$fn.getMesh = function () {
			return {
				vertices: this.vertices.slice(),
				indices: this.indices.slice(),
				materialLibrary: this.materialLibrary,
				maters: this.maters.slice(),
				hasIndex: true
			};
		};

		$fn.clone = function () {
			return {
				vertices: this.vertices.slice(),
				indices: this.indices.slice(),
				materialLibrary: {},
				maters: this.maters.slice(),
				hasIndex: true
			};
		};
	}
	initConstructor();
	initMethods();
})(window.L5);